from django.db import transaction
from rest_framework import generics, views
from utils import response_ok, response_error
from utils.exceptions import CustomError
from utils.permission import IsMemberUser
from .serializers import CommentSerializer
from .models import Comment, CommentLike
from .filters import CommentFilter


class CommentLikeView(views.APIView):
    permission_classes = [IsMemberUser, ]

    def get(self, request, pk):
        try:
            with transaction.atomic():
                comment = Comment.get_instance_by_id(pk)
                # 记录点
                instance, operate = CommentLike.objects.get_or_create(comment=comment, member=request.user.member)
            if operate:
                comment.like_count += 1
                msg = '点赞成功'
            else:
                comment.like_count -= 1
                instance.delete()
                msg = '成功取消点赞'
            comment.save()
            return response_ok(msg)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))


class ActivityCommentListView(generics.ListAPIView):
    serializer_class = CommentSerializer
    queryset = Comment.objects.filter(delete=False)

    def filter_queryset(self, queryset):
        f = CommentFilter(self.request.GET, queryset=queryset)
        return f.qs
